<?php

declare (strict_types=1);

namespace app\home\command;

use helper\SwooleClient;
use helper\SwooleServer;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

class Swoole extends Command
{
    // php think swoole server
    protected function configure()
    {
        // 指令配置
        $this->setName('swoole')
            ->addArgument('name', Argument::OPTIONAL, "function name")
            ->setDescription('the swoole command');
    }

    protected function execute(Input $input, Output $output)
    {
        $name = $input->getArgument('name');
        $func = $name ? trim($name) : 'server';
        if (!method_exists($this, $func)) {
            $output->writeln($func . ':方法不存在');
        }
        $this->$func();
        // 指令输出
        $output->writeln('swoole');
    }

    /**
     * TCP 服务器 服务端
     * @return void
     */
    public function server()
    {
        $server = new SwooleServer();
        $server->set();
        $server->receive();
        $server->task(function ($data) {
            // 处理数据


            echo 'data:' . $data . PHP_EOL;
        });
        $server->start();
    }

    /**
     * TCP 服务器 客户端
     * @return void
     * @throws \Exception
     */
    public function client()
    {
        $client = new SwooleClient();
        $client->coonect()->send(date('Y-m-d H:i:s'));
    }
}